﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Configuration;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Security;

using JohnnySins.DAL;
using JohnnySins.DAL.Repositories;
using JohnnySins.Entities;
using JohnnySins.Code;


namespace JohnnySins.Account
{
    public partial class Login : BasePage
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            LoginUser.LoggingIn += new LoginCancelEventHandler(LoginUser_LoggingIn);
            LoginUser.LoginError += LoginUser_LoginError;
            LoginUser.Authenticate += LoginUser_Authenticate;

            if (!IsPostBack)
            {
                if (this.Request.Cookies["email"] != null && !string.IsNullOrEmpty(Request.Cookies["email"].Value))
                {
                    this.LoginUser.UserName = Request.Cookies["email"].Value;
                    this.LoginUser.RememberMeSet = true;
                }
                DoRedirectIfLogin();
            }
        }

        bool parallelLogins = false;

        private bool TryLogin()
        {
            var validateResult = Membership.ValidateUser(this.LoginUser.UserName, this.LoginUser.Password);

            if (validateResult)
            {
                //111
                if (!CurrentUsers.CanLogin(this.LoginUser.UserName))
                {
                    //parallelLogins = true;
                    LogLoginHelper.AddLogLogin(LoginUser.UserName, LoginUser.Password, new EpochAnswer() { Error = "Duplicate login" });
                    // Temporary allow parallel logins
                    //return false;
                }

                var user = Membership.GetUser(this.LoginUser.UserName);

                User findUser = null;
                using (var userRepo = RepositoryFactory.ResolveRepository<UserRepository>())
                {
                    findUser = userRepo.Find((Guid)user.ProviderUserKey);
                }
                if (findUser == null)
                {
                    LogLoginHelper.AddLogLogin(this.LoginUser.UserName, this.LoginUser.Password, new EpochAnswer());
                    return false;
                }

                if (LoginUser.UserName.ToLower() != "zubair" && LoginUser.UserName.ToLower() != "admin" && LoginUser.UserName.ToLower() != "johnny")
                {
                    EpochAnswer epoLogin = CheckEpochMember.CheckMember(findUser.Email);
                    
                    // Temporary allow bad epoch answer
                    /*
                    findUser.IsActive = epoLogin.IsActive;
                    using (var userRepo = RepositoryFactory.ResolveRepository<UserRepository>())
                    {
                        if (findUser.IsActive)
                        {
                            userRepo.Activate(findUser.Id);
                        }
                        else
                        {
                            userRepo.Deactivate(findUser.Id);
                        }
                    }*/

                    LogLoginHelper.AddLogLogin(this.LoginUser.UserName, this.LoginUser.Password, epoLogin);
                    //return findUser.IsActive;
                    return true;
                }
                else
                {
                    LogLoginHelper.AddLogLogin(this.LoginUser.UserName, this.LoginUser.Password, new EpochAnswer() { IsActive = true, Error = "", Answer = "" });
                    return true;
                }
            }
            else
            {
                //not valid membership
                LogLoginHelper.AddLogLogin(this.LoginUser.UserName, this.LoginUser.Password, new EpochAnswer());
                return false;
            }
        }

        private void DoRedirectIfLogin()
        {
            if (ConfigurationManager.AppSettings["IsDevelopmentEnvironment"] == null)
                if (IsAuthentificated)
                {
                    /*using (var userRepo = RepositoryFactory.ResolveRepository<UserRepository>())
                    {
                        var findUser = userRepo.Find((Guid)CurrentProviderUserId);
                    
                        if (findUser == null) return;
                        if (findUser.Deleted) return;
                        if (!findUser.IsActive) return;

                        CurrentUserId = findUser.Id;
                        CurrentUserName = findUser.UserName;
                    }*/

                    if (Roles.IsUserInRole("admin"))
                    {
                        Response.Redirect(Request.QueryString["RerurnUrl"], endResponse: true);
                    }

                    else if (Roles.IsUserInRole("user"))
                    {
                        var url = "/member/Home.aspx";
                        var queryString = HttpUtility.UrlDecode(Request.QueryString["RerurnUrl"]);
                        if (queryString == url)
                        {
                            Response.Redirect(url, endResponse: true);
                        }

                    }

                }
        }

        private void LoginUser_Authenticate(object sender, AuthenticateEventArgs e)
        {
            if (TryLogin())
            {
                if (LoginUser.RememberMeSet)
                {
                    var cookie = new HttpCookie("email", LoginUser.UserName);
                    cookie.Expires = DateTime.Now.AddYears(1);
                    Response.Cookies.Add(cookie);
                }
                else
                {
                    var cookie = new HttpCookie("email", String.Empty);
                    cookie.Expires = DateTime.Now.AddYears(1);
                    Response.Cookies.Add(cookie);
                }

                FormsAuthentication.SetAuthCookie(LoginUser.UserName, LoginUser.RememberMeSet);

                if (Roles.IsUserInRole(LoginUser.UserName, "admin"))
                {
                    if (Request.QueryString["ReturnUrl"] != null)
                    {
                        Response.Redirect(Request.QueryString["ReturnUrl"], endResponse: true);
                    }
                }

                if (Roles.IsUserInRole(LoginUser.UserName, "user"))
                {
                    var url = "/Member/Home.aspx";
                    var queryString = HttpUtility.UrlDecode(Request.QueryString["ReturnUrl"]);
                    if (queryString == url)
                    {
                        Response.Redirect(url, endResponse: true);
                    }
                }

                else if (Roles.IsUserInRole("user"))
                    Response.Redirect("~/member/Home.aspx", endResponse: true);
            }

            e.Authenticated = false;
        }

        private void LoginUser_LoginError(object sender, EventArgs e)
        {
            if (parallelLogins)
            {
                pnlParallelLogins.Visible = true;
            }
            else
            {
                this.pnlLoginError.Visible = true;
            }
        }

        void LoginUser_LoggingIn(object sender, LoginCancelEventArgs e)
        {
        }        
    }
}
